// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const db = uniCloud.database()
const collection = db.collection("bg-token")


module.exports = {

	// 获取token
	async get() {

		// 从数据库查询
		const res = await collection.get()
		if (res.affectedDocs == 0) {
			// 请求接口，获取token
			const result = await getAccessToken()
			await collection.add({
				...result.data.data
			})

			return {
				...result.data.data
			}
		} else {
			let data = res.data[0]
			let now = Date.now()

			let expiresAt = data.expiresAt

			if (now < expiresAt * 1000) {
				return {
					...data
				}
			} else {
				const result = await getAccessToken()
				await collection.doc(data._id).update({
					...result.data.data
				})

				return {
					...result.data.data
				}
			}
		}






	}
}

const ACCESS_TOKEN_API = "https://developer.toutiao.com/api/apps/v2/token"

async function getAccessToken() {
	const res = await uniCloud.httpclient.request(ACCESS_TOKEN_API, {
		method: 'POST',
		data: {
			appid: "tt5a702ccdc5437f6601",
			secret: "48ac36c3daa6e1a5909b5df7dfcd0f2a0651b54e",
			grant_type: "client_credential"
		},
		contentType: 'json', // 指定以application/json发送data内的数据
		dataType: 'json' // 指定返回值为json格式，自动进行parse
	})
	return res
}